package com.zhkj.shixi.tvplayer.MusicPlayer;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.zhkj.shixi.tvplayer.Interface.IPlayerFileInfo;
import com.zhkj.shixi.tvplayer.Interface.Mp3Poster;
import com.zhkj.shixi.tvplayer.MyMediaPlayer;
import com.zhkj.shixi.tvplayer.PicturePlayer.CommonDialog;
import com.zhkj.shixi.tvplayer.R;
import com.zhkj.shixi.tvplayer.VideoPlayer.VideoPlayOrder;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AudioActivity extends Activity implements IPlayerFileInfo, Mp3Poster {
    private AudioUI audioUI;
    private static final String TAG = "AudioActivity";
    private MusicCtrl musicCtrl;
    private MyMediaPlayer myMediaPlayer;
    private File mFile;
    private List<File> mMusicList;

    private VideoPlayOrder mPlayOrder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio);
        Intent intent = getIntent();
        Toast.makeText(this,intent.getStringExtra("url"),Toast.LENGTH_SHORT).show();
        mFile =new File(intent.getStringExtra("url"));
        mMusicList = Arrays.asList(mFile.getParentFile().listFiles(new typeFilter()));
        myMediaPlayer = new MyMediaPlayer(this);
        musicCtrl = new MusicCtrl(myMediaPlayer,this);
        audioUI = new AudioUI(this);
        mPlayOrder = new VideoPlayOrder(this);
        myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                audioUI.upgradeUiOnChangeFile();
            }
        });
        myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.i(TAG, "onCompletion: "+mPlayOrder.getType());
                mPlayOrder.setPosition(getmMusicList().indexOf(mFile));
                mPlayOrder.setOrderType(mMusicList);
                if (mPlayOrder.getType()==mPlayOrder.ORDER){
                    if (mPlayOrder.getPosition()==mMusicList.size()-1){
                        CommonDialog.Builder builder =new CommonDialog.Builder(AudioActivity.this);
                        builder.setMessage("已经是最后一个文件了");
                        builder.setTitle("提示");
                        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        });
                        builder.setPositiveButton("重新播放", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (mPlayOrder.getPosition() !=getmMusicList().size()) {
                                    mFile = getmMusicList().get(mPlayOrder.getPosition());
                                    musicCtrl.initPlay();
                                    myMediaPlayer.play();
                                    dialog.dismiss();

                                }
                            }
                        });
                        builder.create().show();
                    }else {
                        mPlayOrder.setPosition(mPlayOrder.getPosition()+1);
                        mFile = getmMusicList().get(mPlayOrder.getPosition());
                        musicCtrl.initPlay();
                        myMediaPlayer.play();
                    }

                }else {
                    if (mPlayOrder.getPosition() != getmMusicList().size()) {
                        mFile = getmMusicList().get(mPlayOrder.getPosition());
                        musicCtrl.initPlay();
                        myMediaPlayer.play();
                    }
                }
            }
        });
        musicCtrl.initPlay();
        myMediaPlayer.play();
        audioUI.upgradeUiOnChangeFile();

    }
    public List<File> getmMusicList() {
        return mMusicList;
    }
    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_DPAD_LEFT:
                // TODO: 快退
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                // TODO: 快进
                break;
        }
        return super.onKeyLongPress(keyCode, event);
    }
    @Override
    public File getNowFile() {
        return mFile;
    }
    @Override
    public List<File> getFileList() {
        return mMusicList;
    }

    @Override
    public void setNowFile(File file) {
        mFile =file;

    }
    /**
     * 获取专辑海报
     * @author linjing
     * @return bitmap
     */
    @Override
    public Bitmap getMP3Poster() {
        String url = this.getNowFile().getPath();
        MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(url);
        byte[] picture = mediaMetadataRetriever.getEmbeddedPicture();
        Bitmap bitmap;

        if (picture == null ){

            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.player_audio_cover);
        }else {
            bitmap = BitmapFactory.decodeByteArray(picture,0,picture.length);
        }
        return bitmap;
    }


    @Override
    public void onBackPressed() {
        if(findViewById(R.id.play_listshow).getVisibility() == View.VISIBLE)
        {
            findViewById(R.id.play_listshow).setVisibility(View.INVISIBLE);
            return;
        }
        if(findViewById(R.id.image_listshow).getVisibility()==View.VISIBLE){
            findViewById(R.id.image_listshow).setVisibility(View.INVISIBLE);
            return;
        }
        CommonDialog.Builder builder =new CommonDialog.Builder(this);
        builder.setMessage("是否退出播放");
        builder.setTitle("提醒");
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        builder.setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     *更新专辑海报
     */
    public void updateMp3Poster() {
        audioUI.mp3bg(this.getMP3Poster());
    }


    public MusicCtrl getMusicCtrl() {
        return musicCtrl;

    }

    public VideoPlayOrder getmPlayOrder() {
        return mPlayOrder;
    }

    public AudioUI getAudioUI() {
        return audioUI;
    }


    private static class typeFilter implements FileFilter
    {
        private String fileType;

        private List<String> anyType = new ArrayList<>();
        public typeFilter() {
                final List<String> musicType =  new ArrayList<>();
                musicType.add(".mp3");
                musicType.add(".wav");
                musicType.add(".ogg");
                musicType.add(".ape");
                musicType.add(".flac");
                anyType = musicType;
        }
        public boolean accept(File file) {
            for(int i = 0;i < anyType.size();i++) {
                if(file.getName().toLowerCase().endsWith(anyType.get(i))){
                    return true;
                }
                else if(file.isDirectory()){
                    return false;
                }
            }
            return false;
        }
    }
}
